package com.hmkj.web.controller.index;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.ValidateUtils;
import com.hmkj.core.constant.AliyunCodeKey;
import com.hmkj.core.constant.PhoneCodeKey;
import com.hmkj.core.constant.SessionId;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 注册页面相关controller
 */
@Api(description = "注册页面相关")
@Slf4j
@RestController
@RequestMapping(GenericController.BASE_API_URL + "/userRegister")
public class AppRegisterController extends GenericController<Integer, User> {

    @Resource
    private UserService userService;

    /**
     * 用户注册提交
     *
     * @return
     */
    @ApiOperation(value = "注册接口", notes = "注册接口")
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public ResultEntity register(
            @ApiParam("手机号") @RequestParam String mobilePhone,
            @ApiParam("密码(rsa加密再base64加密)") @RequestParam String password,
            @ApiParam("手机短信") @RequestParam String phoneCode,
            @ApiParam("邀请码（必填）") @RequestParam String fatherPhone,
            HttpServletRequest request) {
        log.info("web用户注册");
        String tempContextUrl = request.getHeader("Origin");
        if (!ValidateUtils.isPhone(mobilePhone)) {
            throw new BussinessException("手机号格式不正确");
        }
        // 校验短信
        checkUserPhoneCode(mobilePhone, phoneCode, PhoneCodeKey.REGISTER);
        userService.doRegister(new UserModel(u -> {
            u.setMobilePhone(mobilePhone);
            u.setPassword(password);
            u.setResource(tempContextUrl);
            if (StrUtil.isNotBlank(fatherPhone)) {
                // 邀请码 找出父级用户id存入新注册的用户
                User inviteUser = userService.selectByMobile(fatherPhone);
                if (null != inviteUser) {
                    u.setInviteId(inviteUser.getId());
                } else {
                    throw new BussinessException("当前邀请码不存在");
                }
            } else {
                throw new BussinessException("请填写邀请码");
            }
        }));
        // 删除短信
        delSession(SessionId.CAPTCHA);
        final User user = userService.selectOne(new User(u -> u.setMobilePhone(mobilePhone)));
        // 注册完成默认登录
        setSession(SessionId.MEMBER_USER, user);
        return ok(m -> m.put("id", user.getId()),"注册成功");
    }

    /**
     * 发送短信接口
     *
     * @return
     */
    @ApiOperation(value = "发送短信接口", notes = "发送短信接口")
    @ResponseBody
    @RequestMapping(value = "msg", method = RequestMethod.POST)
    public ResultEntity msg(
            @ApiParam("手机号") @RequestParam String mobilePhone,
            @ApiParam("cid") @RequestParam String cid,
            @ApiParam("图片验证码") @RequestParam(required = true) String captcha) throws Exception {
        // 校验图片验证码
        checkCaptcha(captcha, cid);
        int i = userService.selectCount(new User(u -> {
            u.setMobilePhone(mobilePhone);
            u.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if (i > 0) {
            throw new BussinessException("手机号码已存在");
        }
        log.info("注册发送短信");
        sendSmsCode(AliyunCodeKey.REGISTER, "用户注册", mobilePhone);
        return ok("注册发送短信成功", ResultEntity.SUCCESS);
    }

    @ApiOperation(value = "注册短信校验", notes = "注册短信校验")
    @ResponseBody
    @RequestMapping(value = "checkMsg", method = RequestMethod.POST)
    public ResultEntity checkMsg(@ApiParam("手机号") @RequestParam String mobilePhone,
                                 @ApiParam("手机短信") @RequestParam String phoneCode) throws Exception {
        log.info("注册短信校验");
        checkUserPhoneCode(mobilePhone, phoneCode, PhoneCodeKey.REGISTER);
        return ok("注册短信校验成功", ResultEntity.SUCCESS);
    }
}
